package com.ding;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.util.ExcelBean;
import com.util.ExcelUtil;
import com.util.FileUtil;

/**
 * @author dingyuanwei
 * @version 建立時間：Dec 1, 20109:24:13 AM
 * 類別說明:
 */
public class exportExcelAction extends ActionSupport {

	private String toCopyPath;//考贝文件到某个目录下的路径
	private String copyPath;
	private String[] magazines;//选定的文件类型
	private InputStream downloadFile;
	
	private String downloadFileName;//下載Excel文件的名字
	 public void setMagazines(String[] codes) {
	        for (String code : codes) {
	            System.out.println(code + " is selected");
	        }
	        magazines  = codes;
	        
	 }
	 
		@Override
		public String execute() throws Exception
		{
			return SUCCESS;
		}
	 
	public InputStream getDownloadFile() 
	{	
		String lastDirName = copyPath.substring(copyPath.lastIndexOf("\\")+1);//最后一个目录名
		Map<String , List<String>> map = FileUtil.ergodicFile(toCopyPath);//写出路径
		
		Date date = new Date();
		String dateecxl = dateToDateString(date,"yyyy-MM-dd");
		//String varName = sel.toLowerCase();//A--allPath  or N---simpleName (全转换成小写)(控件器)
		
		HSSFWorkbook wb = new HSSFWorkbook();//同時構建三個工作區
		String sheetName ="";
        if(magazines != null){//沒有選擇後綴
			for (int i = 0; i < magazines.length; i++) {
				String suffix = magazines[i];
				List<String> listPath =  map.get(magazines[i]);
				if(listPath == null){
					listPath = new ArrayList<String> ();
				}
				
				List listSimple = new ArrayList();
				listSimple = genenaiPathAandN(listPath, "A", lastDirName);//生成前台顯示的數據
				
				ExcelBean excelBean1 = new ExcelBean();
				excelBean1.setWidth(new int[30]);//為全寬設了沒用
				
				
				
				sheetName ="."+ suffix+"_"+listPath.size();
		    	excelBean1.setSheetName(sheetName); //設置工作單名稱
				List<String> titleList = new ArrayList<String>();
				titleList.add("更新日期");
				titleList.add("檔名");
				titleList.add("存放路徑");
				titleList.add("狀態");
				titleList.add("負責人");
				excelBean1.setTitleList(titleList); //設置第一行標題列表
				List excelList = new ArrayList();//数据集也代表多行
				for (Iterator iter = listSimple.iterator(); iter.hasNext();) {
					String element = (String) iter.next();
					List<String> rowList1 = new ArrayList<String>(); //行數據			   	
					rowList1.add(dateecxl); //學期	
					rowList1.add(element.substring(element.lastIndexOf("\\")+1)); //節
					rowList1.add(element);//單元
					rowList1.add(""); //單元編號
					rowList1.add(""); //章
					excelList.add(rowList1);
					
				}
				excelBean1.setDataList(excelList);
				wb = ExcelUtil.creatExcel(wb, excelBean1);
				
				HSSFSheet sheet = wb.getSheet(sheetName);
				sheet.addMergedRegion(new Region(1,(short)0,listPath.size(),(short)0));
			
			}
		
        }
		String root = ServletActionContext.getRequest().getRealPath(
		"/temp");
		downloadFileName = lastDirName+dateecxl+".xls";
		
		boolean flag = ExcelUtil.writeExcel(wb, root+"\\"+downloadFileName);	

		if(flag == true){
			System.out.println("下载成功");
		}else{
			System.out.println("下载失败");
		}
		
//		System.out.println(exportExcelAction.class.getClassLoader().getResource(""));   
//		   
//        System.out.println(ClassLoader.getSystemResource(""));   
//        System.out.println(exportExcelAction.class.getResource(""));   
//        System.out.println(exportExcelAction.class.getResource("/")); 
//        //Class文件所在路径 
//        System.out.println(new File("/").getAbsolutePath());   
//        System.out.println(System.getProperty("user.dir"));   

		InputStream is = ServletActionContext.getServletContext().getResourceAsStream(
				"/temp"+"/"+downloadFileName);
		return is;
		
	}
	
	public static String dateToDateString(Date date, String formatStr) {
		DateFormat df = new SimpleDateFormat(formatStr);
		return df.format(date);
	}
	
//	生成前台顯示路徑數據
	public static List genenaiPathAandN(List<String> listPath, String varName ,String lastDirName){
		List getFilePathList = new ArrayList();
		for (Iterator iterIn = listPath.iterator(); iterIn.hasNext();) {
			String element = (String) iterIn.next();
			//if("A".equalsIgnoreCase(varName)){//找出全称路径
				
				getFilePathList.add(element.substring(element.indexOf(lastDirName)));//全部
				//System.out.println(element.substring(element.indexOf(lastDirName)));
			//}else if("N".equalsIgnoreCase(varName)){
				//getFilePathList.add(element.substring(element.lastIndexOf("\\")+1));//尾
				//System.out.println(element.substring(element.lastIndexOf("\\")+1));//尾
			//}else{
				//if(element.lastIndexOf(varName) != -1){
					//getFilePathList.add(element.substring(element.indexOf(lastDirName)));
					//System.out.println(element.substring(element.indexOf(lastDirName)));
				//}
				
			//}
		
		}
		return getFilePathList;
	}
	
	/**
	 * 生成excel文件
	 * @param map
	 * @return
	 */
	    public String genenaiExcel(Map<String , List<String>> map, String lastDirName){
	    	ExcelBean excelBean1 = new ExcelBean();
	    	String xmlKey = "xml";
	    	String jspKey = "jsp";
	    	
	    	excelBean1.setSheetName(xmlKey+"and"+jspKey); //設置工作單名稱
			List<String> titleList = new ArrayList();
			titleList.add("學期");
			titleList.add("章－名稱");
			titleList.add("節－名稱");
			titleList.add("單元－名稱");
			titleList.add("觀念檔ID");
			excelBean1.setTitleList(titleList); //設置第一行標題列表
			
			List excelList = new ArrayList();//数据集也代表多行
		
			List rowList1 = new ArrayList(); //行數據			   	
			rowList1.add("1"); //學期	
			rowList1.add("2"); //章
			rowList1.add("1"); //節
			rowList1.add("1");//單元
			rowList1.add("1"); //單元編號
			excelList.add(rowList1);
			
			List rowList2 = new ArrayList(); //行數據			   	
			rowList2.add("1"); //學期	
			rowList2.add("2"); //章
			rowList2.add("1"); //節
			rowList2.add("1");//單元
			rowList2.add("1"); //單元編號
			excelList.add(rowList2);
			
			excelBean1.setDataList(excelList);
			
			
			
			String javaKey = "java";
			ExcelBean excelBean2 = new ExcelBean();
			excelBean1.setSheetName(javaKey); //設置工作單名稱
			
			
			
	    	String classKey = "class";
	    	ExcelBean excelBean3 = new ExcelBean();
	    	excelBean1.setSheetName(classKey); //設置工作單名稱
			
			HSSFWorkbook wb = new HSSFWorkbook();//同時構建三個工作區
			wb = ExcelUtil.creatExcel(wb, excelBean1);
			wb = ExcelUtil.creatExcel(wb, excelBean2);
			wb = ExcelUtil.creatExcel(wb, excelBean3);
	    	
	    	
	    	
			String path="LevelType.xls";
			boolean flag = ExcelUtil.writeExcel(wb, path);	
			if(flag == true){
				System.out.println("下载成功");
			}else{
				System.out.println("下载失败");
			}
			return path;
	    }
	    
		public String[] getMagazines() {
			return magazines;
		}

		public String getToCopyPath() {
			return toCopyPath;
		}

		public void setToCopyPath(String toCopyPath) {
			this.toCopyPath = toCopyPath;
		}

		public String getCopyPath() {
			return copyPath;
		}

		public void setCopyPath(String copyPath) {
			this.copyPath = copyPath;
		}

		public void setDownloadFile(InputStream downloadFile) {
			this.downloadFile = downloadFile;
		}

		public String getDownloadFileName() {
			return downloadFileName;
		}

		public void setDownloadFileName(String downloadFileName) {
			this.downloadFileName = downloadFileName;
		}
		
}
